#!/usr/bin/env python
# -*- coding: utf-8 -*-

from functools import partial


class Model(object):

    _name = ''
    _inherit = ''

    def __init__(self, env):
        # self.model = model
        self.model = self._inherit or self._name
        self.env = env
        self.rpc = env.rpc

    def __getattr__(self, attr):
        # print()
        return partial(self.rpc.web_dataset_call_kw, self.model, attr)

    def rpccall(self, method, *args, **kwargs):
        return self.rpc.web_dataset_call_kw(self.model, method, *args, **kwargs)

    # 必须显式 定义 所有函数, 否则 super 出错
    def search(self, *args, **kwargs):
        print('in models')
        return self.rpccall('search', *args, **kwargs)

    def search_read(self, *args,  **kwargs):
        return self.rpccall('search_read', *args,  **kwargs)

    # 需要搬家到 odoorpc 中的

    def rpc_find_or_create(self, domain, values):
        res = self.search(domain, limit=1)
        if res:
            return res[0]
        res = self.create(values)
        return res[0]

    def rpc_update_or_create(self, domain, values):
        res = self.search(domain, limit=1)
        if res:
            self.write(res, values)
            return res[0]

        res = self.create(values)
        return res[0]
